package com.town.garden.service.impl;

import com.town.garden.chain.AbstractServerStartHandler;
import com.town.garden.constant.GlobalConstant;
import com.town.garden.entiy.response.SearchSystemInfoResponse;
import com.town.garden.enums.NVRApiEnum;
import com.town.garden.propertites.NvrProperties;
import com.town.garden.service.NvrSystemInfoService;
import com.town.garden.storage.NvrSessionStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/5/13
 */
@Service(NvrSystemInfoServiceImpl.BEAN_NAME)
@Slf4j
public class NvrSystemInfoServiceImpl extends AbstractServerStartHandler implements NvrSystemInfoService, Runnable {
    public static final String BEAN_NAME = "nvrSystemInfoServiceImpl";
    /**
     * 下一个责任链对象
     * {@linkplain NvrIpcListInfoServiceImpl}
     */
    @Autowired
    @Qualifier(NvrIpcListInfoServiceImpl.BEAN_NAME)
    private AbstractServerStartHandler abstractServerStartHandler;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private NvrProperties nvrProperties;
    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Override
    public ResponseEntity<SearchSystemInfoResponse> searchSystemInfo() {
        //拼接请求url
        final String url = GlobalConstant.HTTPS_PREFIX + nvrProperties.getNvrServerIp() + NVRApiEnum.SYSTEM_INFO.getUrl();
        final HttpEntity<?> entity = new HttpEntity<>(null, NvrSessionStorage.headers);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, SearchSystemInfoResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void handlerOperation() {
        //启动定时查询系统详情定时任务
        ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, 0, nvrProperties.getSearchSystemInfoTime(), TimeUnit.SECONDS);
        //调用下一个责任链
        abstractServerStartHandler.handlerOperation();
    }

    @Override
    public void run() {
        ResponseEntity<SearchSystemInfoResponse> searchSystemInfoResponseResponseEntity = searchSystemInfo();
       // log.info("search systemInfo response is :{}", JSONUtil.parse(searchSystemInfoResponseResponseEntity.getBody()));
    }
}
